from django import forms
from django.utils.translation import gettext_lazy as _
from .models import CursorRule, Tag

class CursorRuleForm(forms.ModelForm):
    """Cursor规则表单"""
    
    class Meta:
        model = CursorRule
        fields = ['title', 'content', 'tags']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '规则标题'}),
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 10, 'placeholder': '请输入规则内容...'}),
            'tags': forms.CheckboxSelectMultiple(),
        }
        help_texts = {
            'title': _('请输入规则的标题，建议简洁明了'),
            'content': _('请输入完整的规则内容，支持markdown格式'),
            'tags': _('请选择适合的标签，可以选择多个'),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 将标签按类别分组
        language_tags = Tag.objects.filter(category='language')
        scenario_tags = Tag.objects.filter(category='scenario')
        self.fields['tags'].queryset = Tag.objects.all()
        self.fields['tags'].widget.choices = [
            ('编程语言', [(tag.id, tag.name) for tag in language_tags]),
            ('使用场景', [(tag.id, tag.name) for tag in scenario_tags]),
        ]
    
    def clean_content(self):
        """验证内容字段"""
        content = self.cleaned_data.get('content')
        if len(content) < 10:
            raise forms.ValidationError(_('规则内容太短，请至少输入10个字符'))
        return content 